package com.nervenets.web.controller.handler.user.wealth;

import com.alibaba.fastjson.JSONArray;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.AuthStatus;
import com.nervenets.web.enumeration.FlowStatus;
import com.nervenets.web.hibernate.domain.user.RewardInvoice;
import com.nervenets.web.hibernate.domain.user.WealthFlow;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class UserRewardInvoiceHandler extends Handler<UserRewardInvoiceParams> {
    @Override
    public String handle(UserRewardInvoiceParams params, HttpServletRequest request) throws Exception {
        try {
            JSONArray.parseArray(params.getCerts(), String.class);
        } catch (Exception e) {
            return errorMessage(MessageCode.code_444, "凭证格式不正确");
        }

        List<InvoiceFlow> flowIds;
        try {
            flowIds = JSONArray.parseArray(params.getFlows(), InvoiceFlow.class);
        } catch (Exception e) {
            return errorMessage(MessageCode.code_444, "flowIds格式不正确");
        }

        if (null == flowIds || flowIds.isEmpty()) return errorMessage(MessageCode.code_444, "请选择提现记录");

        for (int i = 0; i < flowIds.size(); i++) {
            InvoiceFlow flow = flowIds.get(i);

            final WealthFlow wealthFlow = userDao.findById(flow.getFlowId(), WealthFlow.class);
            if (null == wealthFlow) return errorMessage(MessageCode.code_404, String.format("第%s条ID记录不存在", i + 1));
        }

        RewardInvoice rewardInvoice = new RewardInvoice(params.getUserId(), params.getFlows(), params.getExpressName(), params.getExpressNumber(), params.getCerts(), AuthStatus.checking, "无");
        userDao.saveOrUpdate(rewardInvoice);

        for (InvoiceFlow flow : flowIds) {
            final WealthFlow wealthFlow = userDao.findById(flow.getFlowId(), WealthFlow.class);
            wealthFlow.setFlowStatus(FlowStatus.verify);
            userDao.saveOrUpdate(wealthFlow);
        }

        return successMessage();
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
